package com.jeremyfeinstein.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Create by sunxunchao on 2019/5/23
 */
public class FileUtil {

    private static final String TAG = "FileUtil";

    /**
     * 获取文件夹下所有的文件名
     *
     * @param folderPath
     * @return
     */
    public static String getFolderFileNames(String folderPath) {
        File file = new File(folderPath);
        StringBuilder sb = new StringBuilder();
        if (file.exists()) {
            File[] subFile = file.listFiles();
            if (subFile == null || subFile.length == 0) {
                return "";
            } else {
                for (File file1 : subFile) {
                    if (file1.isFile()) {
                        sb.append(file1.getName()).append(",");
                    }
                }
                return sb.toString().substring(0, sb.toString().length() - 1);
            }
        } else {
            return "";
        }
    }

    /**
     * 压缩多文件
     *
     * @param filePaths 需要压缩的文件
     * @param savePath  压缩后的文件路径 zip
     * @return
     */
    public static String compressFilesToZip(String[] filePaths, String savePath) {
        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(savePath);
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            for (String filePath : filePaths) {
                if (!TextUtils.isEmpty(filePath)) {
                    File file = new File(filePath);
                    if (file.isFile()) {
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zipOutputStream.putNextEntry(zipEntry);
                        byte[] buffer = new byte[1024];  //缓冲区，每次操作大小
                        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                        while (true) {
                            int len = bis.read(buffer);
                            if (len == -1)
                                break;
                            zipOutputStream.write(buffer, 0, len);
                        }
                        bis.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                zipOutputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (new File(savePath).exists()) {
            return savePath;
        }
        return "";
    }

    /**
     * 解压zip文件
     *
     * @param zipFilePath
     * @param saveToFolderPath
     */
    public static void decompressionZipToFiles(String zipFilePath, String saveToFolderPath) {
        File zipFile = new File(zipFilePath);
        if (zipFile.exists()) {
            ZipInputStream zipInputStream = null;
            try {
                zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
                ZipEntry zipEntry;
                while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                    File file = new File(saveToFolderPath + File.separator + zipEntry.getName());
                    Log.d(TAG, "decompressionZipToFiles: " + file.getName());
                    if (file.isDirectory()) {
                        file.mkdirs();
                    } else {
                        if (file.exists()) {
                            file.delete();
                        }
                        int pos;
                        byte[] buf = new byte[1024];
                        OutputStream bos = new FileOutputStream(file);
                        while ((pos = zipInputStream.read(buf, 0, 1024)) > 0) {
                            bos.write(buf, 0, pos);
                        }
                        bos.flush();
                        bos.close();
                    }
                    zipInputStream.closeEntry();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (zipInputStream != null) {
                    try {
                        zipInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    private static final String[] units = {"B", "KB", "MB", "GB", "TB"};

    /**
     * 单位转换
     */
    public static String getUnit(float size) {
        int index = 0;
        while (size > 1024 && index < 4) {
            size = size / 1024;
            index++;
        }
        return String.format(Locale.getDefault(), " %.2f %s", size, units[index]);
    }


    public static boolean openFolder(Context context, String path, String pkgName) {
        File file = new File(path);
        return openFolder(context, file, pkgName);
    }

    public static boolean openFolder(Context context, File file, String pkgName) {
        if (file == null || !file.exists()) {
            return false;
        }
        Intent intent = intentForFolder(context, file.getAbsolutePath(), pkgName);
        if (intent != null) {
            context.startActivity(intent);
            return true;
        } else {
            return false;
        }
    }

    public static Intent intentForFolder(Context context, String path, String pkgName) {
        File file = new File(path);
        if (file == null || !file.exists()) {
            return null;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0以上
            //7.0以上跳转系统文件需用FileProvider
            Uri uri = FileProvider.getUriForFile(context, pkgName + ".FileProvider", file);
            intent.setData(uri);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        } else {
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "*/*");
        }
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            return intent;
        } else {
            return null;
        }
    }


    public static String getFileParentPath(String path){
        return path.substring(0, path.lastIndexOf(File.separator) + 1);
    }

    /**
     * 获取文件名及后缀
     */
    public static String getFileNameWithSuffix(String path) {
        if(TextUtils.isEmpty(path)){
            return "";
        }
        int start = path.lastIndexOf("/");
        if (start != -1 ) {
            return path.substring(start + 1);
        } else {
            return "";
        }
    }

    private static final String[] suffixs = new String[]{"doc","docx","xls","xlsx","ppt","pptx","pdf","jpg","png","gif","jpeg","ceb","cebx","txt","img","zip"};
    public static boolean suffixConcat(String suffix){
        for (String s : suffixs){
            if (s.equals(suffix)){
                return true;
            }
        }
        return false;
    }

}
